package com.lj.back.manage.scaffold.module.kaptcha;

import com.google.code.kaptcha.Producer;
import com.lj.back.manage.scaffold.common.DTO.ValidCodeDTO;
import com.lj.back.manage.scaffold.common.enums.ResponseEnum;
import com.lj.back.manage.scaffold.common.exception.MyException;
import com.lj.back.manage.scaffold.common.response.ResponseCodeConstant;
import com.lj.back.manage.scaffold.common.util.CommonUtil;
import com.lj.back.manage.scaffold.module.kaptcha.service.KaptchaService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

/**
 * 图形验证码
 * @author lv
 * @version 1.0.0
 */
@Component
@Slf4j
@AllArgsConstructor
public class KaptchaUtil {
    private final KaptchaService kaptchaService;

    private final Producer producer;

    private final HttpServletResponse response;

    /**
     * 生成验证码
     */
    public void render(String key){
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        try(OutputStream out = response.getOutputStream()){
            boolean isSuccess = kaptchaService.record(key, text);
            if (!isSuccess){
                throw new MyException(ResponseCodeConstant.CODE_GRAPH_CREATE_FAIL, "记录验证码失败");
            }
            //写出图片
            ImageIO.write(image, "jpg", out);
        } catch (Exception e) {
            log.error("渲染验证码异常",e);
            kaptchaService.delete(key);
            throw new MyException(ResponseEnum.CODE_GRAPH_CREATE_FAIL);
        }
        //禁止缓存
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        //设置响应格式为图片
        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
    }

    /**
     * 渲染验证码
     */
    public void render(){
        String key = CommonUtil.getUUID();
        response.setHeader("key",key);
        render(key);
    }

    /**
     * 校验验证码
     * @param validCodeDTO 验证码对象
     * @return 校状态码校验枚举类
     */
    public ResponseEnum valid(ValidCodeDTO validCodeDTO){
        return kaptchaService.valid(validCodeDTO.getKey(),validCodeDTO.getCode());
    }
}
